package com.atomic.test.example.service.impl;

import com.atomic.test.example.entity.LoginLog;
import com.atomic.test.example.entity.User;
import com.atomic.test.example.repository.LoginLogRepository;
import com.atomic.test.example.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by dreamyao on 2017/3/6.
 */
@Service
public class LoginLogServiceImpl implements Observer {

    private Observable observable;
    @Autowired
    private LoginLogRepository loginLogRepository;

    /**
     * 注册观察者
     * @param observable
     */
    public LoginLogServiceImpl(Observable observable) {
        this.observable=observable;
        observable.addObserver(this);
    }

    /**
     * This method is called whenever the observed object is changed. An
     * application calls an <tt>Observable</tt> object's
     * <code>notifyObservers</code> method to have all the object's
     * observers notified of the change.
     *
     * @param o   the observable object.
     * @param arg an argument passed to the <code>notifyObservers</code>
     */
    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof UserServiceImpl) {
            HttpServletRequest request= UserContext.getRequest();
            User user=(User)arg;
            // 写入登录日志
            LoginLog loginLog = new LoginLog();
            loginLog.setIp(request.getRemoteAddr());
            loginLog.setUserId(user.getId());
            loginLog.setLoginDataTime(new Date());
            loginLogRepository.save(loginLog);
        }
    }
}
